﻿/*
 * chksum.h
 *
 */
#ifndef __GDK_CHKSUM_H__
#define __GDK_CHKSUM_H__

#include <gdk/core/Types.h>


namespace gdk
{


	__INLINE__ uint16_t chksum(const void *data, int len)
	{
		int32_t sum = 0;  /* assume 32 bit long, 16 bit short */

		while (len > 1) {
			sum += *((uint16_t*)data);
			if (sum & 0x80000000)   /* if high order bit set, fold */
				sum = (sum & 0xFFFF) + (sum >> 16);
			data = (const char*)data + 2;
			len -= 2;
		}

		if (len)       /* take care of left over byte */
			sum += (uint16_t)*(uint8_t *)data;

		while (sum >> 16)
			sum = (sum & 0xFFFF) + (sum >> 16);

		return (uint16_t)(~sum);
	}


}


#endif /* __GDK_CHKSUM_H__ */
